import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import movierecomending.Service;

import org.apache.xmlbeans.XmlException;
import org.example.comunicationInputSchema.ReccomendedCinemaDocument;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import data.CinemaScore;

@SuppressWarnings("serial")
public class TestXMLServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(TestXMLServlet.class.getName());

	private ServletConfig config;
	Service service;
	
	public void init(ServletConfig config) throws ServletException{
		super.init(config);
/*		this.config=config;
		ServletContext context = this.config.getServletContext();				
		try {
			service=new Service(context.getInitParameter("matrixPath"));
		} catch (Exception e) {
			e.printStackTrace();
		}	
*/	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
	
		resp.setContentType("test/xml");
		resp.setCharacterEncoding("UTF-8");
		
		BufferedReader br = req.getReader();
		StringBuffer envelope = new StringBuffer();
		String line;
		while ((line = br.readLine()) != null) {  
			envelope.append(line);  
		}  
		br.close();
		String env = new String(envelope);
		System.out.println("XML RICEVUTO scritto sul file : "+"/home/marco/TestXMLBeans/input.xml");
		PrintWriter pwf = new PrintWriter("/home/marco/TestXMLBeans/input.xml");
		pwf.print(env);
		pwf.flush();

/*
		ReccomendedCinemaDocument rcs = null;
		
		try {
			service.getInput(env);
			HashMap<Integer,CinemaScore> reccomendedCinema=service.computeReccomendingScore();			
			rcs = service.sendResponse(reccomendedCinema);
		} catch (XmlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
*/
		
 		FileReader fr = new FileReader("/home/marco/TestXMLBeans/output.xml");
		
		br = new BufferedReader(fr);
		StringBuffer result = new StringBuffer();
		while ((line = br.readLine()) != null) 
			result.append(line);

		PrintWriter pw = resp.getWriter();
		pw.print(result.toString());
		pw.flush();
/*
		String out = "Errore";
		if(rcs!=null)
			out = rcs.toString();
			
		PrintWriter pw = resp.getWriter();
		pw.print(out);
		pw.flush();
*/
	} 	
}
